package com.rupertjones.globalcron.client.messaging;

import com.rupertjones.globalcron.common.messaging.ConfigurationRequest;
import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;

import java.net.UnknownHostException;

/**
 * <p>&copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class ClientInitialisationJob implements Runnable {

    private static final Logger LOG = Logger.getLogger(ClientInitialisationJob.class);

    private final JmsTemplate outgoingMessagesTemplate;

    public ClientInitialisationJob(JmsTemplate outgoingMessagesTemplate) {
        this.outgoingMessagesTemplate = outgoingMessagesTemplate;
    }

    @Override
    public void run() {
        LOG.info("Requesting configuration from server");
        outgoingMessagesTemplate.convertAndSend(new ConfigurationRequest(getHostname()));
    }

    private String getHostname() {
        String hostname = null;
        try {
            hostname = java.net.InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return hostname;
    }
}
